package com.itheima.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.vo.UserVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class AnalysisManager {

    @DubboReference
    AnalysisByDayService analysisByDayService;

    public ResponseEntity findSummary() {
        return ResponseEntity.ok(analysisByDayService.findSummary());
    }


    //同比新增、活跃用户、次日留存率
    public ResponseEntity users(Long sd, Long ed, Integer type) {
        //1.调用rpc查询今年数据
        String thisYearStartTime = DateUtil.formatDate(new Date(sd));
        String thisYearEndTime = DateUtil.formatDate(new Date(ed));
        List<UserVo> thisYearVoList = getUserVoList(thisYearStartTime, thisYearEndTime, type);

        //2.调用roc查询去年数据
        String lastYearStartTime = DateUtil.offsetMonth(new Date(sd), -12).toDateStr();
        String lastYearEndTime = DateUtil.offsetMonth(new Date(ed), -12).toDateStr();
        List<UserVo> lastYearVoList = getUserVoList(lastYearStartTime, lastYearEndTime, type);
        //封装并返回
        Map resultMap = new HashMap();
        resultMap.put("thisYear", thisYearVoList);
        resultMap.put("lastYear", lastYearVoList);
        return ResponseEntity.ok(resultMap);
    }

    //封装UserVoList
    public List<UserVo> getUserVoList(String startTime, String endTime, Integer type) {
        List<AnalysisByDay> analysisByDayList = analysisByDayService.findAnalysisByDayList(startTime, endTime);
        //声名voList
        List<UserVo> voList = new ArrayList<>();
        //遍历
        if (CollectionUtil.isNotEmpty(analysisByDayList)) {
            for (AnalysisByDay analysisByDay : analysisByDayList) {
                //设置vo
                UserVo vo = new UserVo();
                //判断type
                if (type == 101) {//今日注册用户
                    vo.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));//日期
                    vo.setAmount(analysisByDay.getNumRegistered());//新注册用户数
                } else if (type == 102) {//今日活跃用户
                    vo.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));//日期
                    vo.setAmount(analysisByDay.getNumActive());//今日活跃数
                } else if (type == 103) {//次日留存率
                    vo.setTitle(DateUtil.formatDate(analysisByDay.getRecordDate()));//日期
                    vo.setAmount(analysisByDay.getNumRetention1d());//次日留存用户数
                }
                //添加集合
                voList.add(vo);
            }
        }

        return voList;
    }
}
